import Axios, { AxiosError } from "axios";
import { router } from "@/router/index"
import { useUserStore } from "@/store";
import { ElMessage } from "element-plus";
const instance = Axios.create({
    baseURL: "http://xue.cnkdl.cn:9082/mall-admin/",
    timeout: 5000
})
instance.interceptors.request.use(confirm => {
    const token = localStorage.getItem('token')
    if (token) {
        // if (confirm.headers) {
        //     confirm.headers['Authorization'] = token
        // }
        confirm.headers && (confirm.headers['Authorization'] = token)

    }
    return confirm

}, err => Promise.reject(err)
)

instance.interceptors.response.use(res => {
  
    const store = useUserStore()
    if (res.data.code === 401) {
        localStorage.removeItem("token")
        // 页目跳转到登录页面
        router.push('/login')
        //  删除路由
        store.activeMenus.forEach(item =>
            router.removeRoute(item.name)
        )
        router.removeRoute("home")
        // setTimeout(() => {
        //     console.log(router.getRoutes());
        // }, 2000);
        //  清除pinia中数据
        store.username = ""
        store.menus = []
        ElMessage.error(res.data.message);
    }

    return res.data

}, (err: AxiosError) => {
    // console.log(err.message);

    ElMessage.error(`操作失败，请联系管理员${err.message}`)
    return Promise.reject(err)
}
)

export default instance